package com.vanzo.some.test;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;

/**
 * Created by tisen on 2017/10/24.
 */

public class UserTypeAdapter extends TypeAdapter<User> {
    @Override
    public void write(JsonWriter out, User value) throws IOException {
        out.beginObject();
        out.name("姓名").value(value.getName());
        out.name("年龄").value(value.getAge());
        out.name("性别").value(value.getSex());
        out.name("朋友").value(valueToString(value.getFriends()).toString());
        out.endObject();
    }

    @Override
    public User read(JsonReader in) throws IOException {
        final User user = new User();
        in.beginObject();
        while (in.hasNext()) {
            switch (in.nextName()) {
                case "姓名":
                    user.setName(in.nextString());
                    break;
                case "年龄":
                    user.setAge(in.nextInt());
                    break;
                case "性别":
                    user.setSex(in.nextInt());
                    break;
                case "朋友":
                    user.setFriends(stringToValue(in.nextString()));
                    break;
            }
        }
        in.endObject();

        return user;
    }

    private String valueToString(String[] list) {
        if (list == null || list.length == 0) {
            return null;
        } else {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(list[0]);
            for (int i = 1; i < list.length; i++) {
                stringBuffer.append("," + list[i]);
            }
            return stringBuffer.toString();
        }
    }

    private String[] stringToValue(String s) {
        return s.split(",");
    }
}
